<template>
  <div class="p-4">
    <div class="search_form">
      <Form ref="formRef" :model="searchForm" layout="inline">
        <FormItem label="日期" name="time" class="form_item_box">
          <RangePicker
            v-model:value="searchForm.time"
            format="YYYY-MM"
            :mode="['month', 'month']"
            @panelChange="handlePanelChange"
            :style="{ width: '200px' }"
          ></RangePicker>
        </FormItem>
      </Form>
      <div class="search_btn"
        ><a-button type="primary" @click="getTableData">查询</a-button>
        <a-button @click="searchFormReset">重置</a-button>
      </div>
    </div>
    <div class="add_project">
      <a-button type="primary" @click="goEdit('add')" v-if="isButtonVisible(20000001)"
        >添加项目</a-button
      >
    </div>
    <div class="ant_table">
      <Table
        style="height: 100%"
        :dataSource="dataSource"
        :columns="columns"
        :pagination="pagination"
        @change="tableChangeFn"
      >
        <!-- <template #contract="{ record }">
          <div class="file_download" @click="fileDownloadFn(record)">附件下载</div>
        </template> -->
        <template #action="{ record }">
          <Popover trigger="click" placement="leftTop">
            <template #content
              ><div class="action">
                <div
                  class="action_btn"
                  @click="goEdit('edit', record)"
                  v-if="isButtonVisible(20000002)"
                  >修改</div
                >
                <Popconfirm
                  :title="`您确定要删除${record.name}吗？`"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="confirmDeletion(record)"
                >
                  <div class="action_btn" v-if="isButtonVisible(20000003)">删除</div>
                </Popconfirm>
                <div
                  class="action_btn"
                  @click="showProjectRequestRecord(record)"
                  v-if="record.createStaffType == '1' && userInfor.type == '1' && record.my == true"
                  >申请盖章</div
                >
                <!-- <div class="action_btn" @click="showProjectRequestRecord(record)">申请记录</div> -->
                <div class="action_btn" @click="showViewRecord(record)">查看记录</div>
              </div>

              <Popover trigger="click" placement="leftTop">
                <template #content>
                  <div
                    class="action_btn"
                    type="primary"
                    v-for="(item, index) in recordsArr"
                    :key="index"
                    @click="selectAddKind(item.kind, record)"
                    >添加{{ item.name }}</div
                  >
                </template>
                <div
                  class="action_btn"
                  v-if="record.createStaffType == '0' && userInfor.type == '0'"
                  >增加记录</div
                >
                <div
                  class="action_btn"
                  v-if="record.createStaffType == '1' && userInfor.type == '1' && record.my == true"
                  >添加申请记录</div
                >
              </Popover>
            </template>
            <div class="action_btn">操作</div>
          </Popover>
        </template>
      </Table>
    </div>
    <!-- 查看记录 -->
    <ViewRecord ref="ViewRecordRef" />
    <!--项目申请记录 -->
    <ProjectRequestRecord ref="ProjectRequestRecordRef" />
    <!-- 合同记录 -->
    <ContractRecords ref="contract" @tableNeedUpdate="tableNeedUpdate" />
    <!-- 验收记录 -->
    <AcceptanceRecords ref="acceptance" @tableNeedUpdate="tableNeedUpdate" />
    <!-- 招投标记录 -->
    <BiddingRecords ref="bidding" @tableNeedUpdate="tableNeedUpdate" />
    <!-- 出图记录 -->
    <DrawingRecord ref="brawing" @tableNeedUpdate="tableNeedUpdate" />
    <!-- 发票记录 -->
    <InvoiceRecord ref="invoice" @tableNeedUpdate="tableNeedUpdate" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive, onActivated } from 'vue';
  import { Table, message, Popconfirm, Popover, DatePicker, Form, FormItem } from 'ant-design-vue';
  import {
    getProjectMyQueryaApi,
    delProjectManagementList,
    fileViewApi,
    fileDownloadApi,
  } from '/@/api/projectManagement';

  import { useRouter, useRoute } from 'vue-router';
  import qs from 'qs';
  import ViewRecord from './components/ViewRecord.vue';
  import ContractRecords from './components/ContractRecords.vue'; //合同记录
  import AcceptanceRecords from './components/AcceptanceRecords.vue'; //验收记录
  import BiddingRecords from './components/BiddingRecords.vue'; //招投标记录
  import DrawingRecord from './components/DrawingRecord.vue'; //出图记录
  import InvoiceRecord from './components/InvoiceRecord.vue'; //发票记录
  import ProjectRequestRecord from './components/ProjectRequestRecord.vue'; //项目申请记录
  import { queryAllLicense } from '/@/api/api';
  import moment from 'moment';
  let RangePicker = DatePicker.RangePicker;

  let route = useRoute();
  const isButtonVisible = (id) => {
    let rulesArr = route?.meta?.rules?.map((rule) => rule.id) || [];
    return rulesArr.includes(id);
  };
  const userInfor = ref();
  const router = useRouter();
  onMounted(() => {
    userInfor.value = JSON.parse(localStorage.getItem('userInfor'));
    getTableData();
    queryAllLicense().then((res) => {
      allLicense.value = res;
    });
  });
  onActivated(() => {
    console.log('出发');
    getTableData();
  });
  // 获取列表数据
  const getTableData = () => {
    getProjectMyQueryaApi({
      page: pagination.value.current,
      limit: pagination.value.pageSize,
      createDateStart:
        searchForm.time.length > 0 ? moment(searchForm.time?.[0]).format('YYYY-MM') : undefined,
      createDateEnd:
        searchForm.time.length > 0 ? moment(searchForm.time?.[1]).format('YYYY-MM') : undefined,
    }).then((res) => {
      if (res.items) {
        pagination.value.total = res.total || 0;
        dataSource.value = res.items || [];
      }

      console.log(res, 'res');
    });
  };

  //跳转新增/编辑
  const goEdit = (action = 'add', data = []) => {
    let url = '';
    if (action == 'add') {
      url = '/dashboard/addProject';
    } else {
      url = `/dashboard/editProject?${qs.stringify(data)}`;
    }
    router.push(url);
  };

  const ViewRecordRef = ref();
  const showViewRecord = (record) => {
    let auth = !(record.createStaffType == '0' && userInfor?.type == '0');
    ViewRecordRef.value.init({
      id: record.id,
      auth,
    });
  };

  const ProjectRequestRecordRef = ref();
  const showProjectRequestRecord = (record) => {
    ProjectRequestRecordRef.value.init({
      id: record.id,
    });
  };

  //列表数据
  const dataSource = ref([]);

  // 列表配置
  const columns = ref([
    {
      title: '项目编号',
      align: 'left',
      dataIndex: 'code',
      fixed: 'left',
    },
    // {
    //   title: '公司编号',
    //   align: 'left',dataIndex: 'companyId',
    //   key: 'companyId',
    //
    //
    // },
    // {
    //   title: '公司名称',
    //   align: 'left',dataIndex: 'companyName',
    //   key: 'companyName',
    //
    //
    // },
    {
      title: '项目名称',
      align: 'left',
      dataIndex: 'name',
      key: 'name',
    },

    {
      title: '累计合同金额',
      align: 'left',
      dataIndex: 'totalContractAmount',
      key: 'totalContractAmount',
    },
    {
      title: '累计发票金额',
      align: 'left',
      dataIndex: 'totalInvoinceAmount',
      key: 'totalInvoinceAmount',
    },
    {
      title: '项目地址',
      align: 'left',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '甲方',
      align: 'left',
      dataIndex: 'firstParty',
      key: 'firstParty',
    },
    {
      title: '合伙人',
      align: 'left',
      dataIndex: 'createStaffName',
      customRender: ({ record }) => {
        return record.createStaffType == '1' ? record.createStaffName : '-';
      },
    },
    // {
    //   title: '验收内容',
    //   align: 'left',dataIndex: 'checkContent',
    //   key: 'checkContent',
    //   width: 200,
    //
    // },
    // {
    //   title: '验收时间',
    //   align: 'left',dataIndex: 'checkDate',
    //   key: 'checkDate',
    //
    //
    // },
    // {
    //   title: '合同附件',
    //   align: 'left',dataIndex: 'contract',
    //   key: 'contract',
    //   slots: { customRender: 'contract' },
    //
    // },
    // {
    //   title: '出图类型',
    //   align: 'left',dataIndex: 'designType',
    //   key: 'designType',
    //
    //
    // },
    // {
    //   title: '出图时间',
    //   align: 'left',dataIndex: 'designDate',
    //   key: 'designDate',
    //
    //
    // },
    // {
    //   title: '开票信息',
    //   align: 'left',dataIndex: 'invoice',
    //   key: 'invoice',
    //   width: 200,
    //
    // },
    {
      title: '添加时间',
      align: 'left',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      align: 'left',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
      width: 80,
    },
  ]);

  // 删除项目
  const confirmDeletion = (record) => {
    delProjectManagementList({
      id: record.id,
    }).then(() => {
      message.success('删除成功');
      getTableData();
    });
  };

  // 合同附件下载
  // const fileDownloadFn = (record) => {
  //   fileDownloadApi(`${record.contract}`).then((res) => {
  //     console.log(res, '测试');
  //     download(res, `${record.name}合同附件.${record.contract.split('.')[1]}`);
  //   });
  // };
  // blob下载
  // const download = (blob, name) => {
  //   const link = document.createElement('a'); //创建一个a标签
  //   const url = window.URL.createObjectURL(blob); //将blob文件对象通过URL.createObjectURL()方法转为为url
  //   link.href = url; //为a标签设置href属性，并赋值为url
  //   link.download = name; //定义下载的文件名，文件名要包含后缀哟！如'导出EXCEL.xlsx'
  //   document.body.appendChild(link); //把a标签放在body上
  //   link.click(); //出发a标签点击下载
  //   document.body.removeChild(link); //在body中移除这个a标签
  //   URL.revokeObjectURL(url); //释放blob对象
  // };

  //分页器对象
  const pagination = ref({
    current: '1',
    pageSize: '10',
    pageSizeOptions: ['10', '20', '50', '100'],
    total: 0,
    showTotal: (totals) => `总${totals}条数据`,
    showSizeChanger: true,
  });

  // table变化时出发  筛选/跳转
  const tableChangeFn = (e) => {
    pagination.value.current = String(e.current);
    pagination.value.pageSize = String(e.pageSize);
    console.log(e, 'e');
    getTableData();
  };

  // 跳转到增加记录
  const goAdditionRecord = (record) => {
    router.push(`/dashboard/addRecords?id=${record.id}`);
  };

  const recordsArr = ref([
    {
      name: '合同记录',
      kind: 'hetong',
    },
    {
      name: '出图记录',
      kind: 'chutu',
    },
    {
      name: '发票记录',
      kind: 'fapiao',
    },
    {
      name: '招投标记录',
      kind: 'zhao',
    },
    {
      name: '验收记录',
      kind: 'yan',
    },
  ]);

  const acceptance = ref(); //验收
  const bidding = ref(); //招投标
  const brawing = ref(); //出图
  const invoice = ref(); //发票
  const contract = ref(); //合同
  const allLicense = ref([]);
  const selectAddKind = (kind, record) => {
    // 增加记录弹窗需要区分是分公司还是合伙人，合伙人显示添加申请
    let projectKind = '';
    if (record.createStaffType == '0' && userInfor.value.type == '0') {
      console.log('是分公司项目');
    }
    if (record.createStaffType == '1' && userInfor.value.type == '1' && record.my == true) {
      console.log('是合伙人项目');
      projectKind = 'partner';
    }
    let data = {
      allLicense: allLicense.value,
      isEdit: false,
      projectId: record.id,
      projectKind: projectKind,
    };
    if (kind == 'hetong') {
      contract.value.init(data);
    } else if (kind == 'chutu') {
      brawing.value.init(data);
    } else if (kind == 'fapiao') {
      invoice.value.init(data);
    } else if (kind == 'zhao') {
      bidding.value.init(data);
    } else if (kind == 'yan') {
      acceptance.value.init(data);
    }
  };

  const tableNeedUpdate = () => {
    getTableData();
  };

  // 搜索表单参数
  const searchForm = reactive({
    time: [],
  });
  // 搜索表单参数重置
  const searchFormReset = () => {
    console.log(searchForm, 'searchForm');
    searchForm.time = [];
    getTableData();
  };
  // 日期面板变化时的回调
  const handlePanelChange = (val) => {
    searchForm.time = val;
  };
</script>

<style lang="less" scoped>
  .add_project {
    margin-bottom: 10px;
  }
  .action_btn {
    color: #1990ff;
    cursor: pointer;
    margin: 5px 0;
  }
  .file_download {
    cursor: pointer;
    color: rgba(0, 175, 233);
  }

  .search_form {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 90px;
    .search_btn {
      width: 10%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      > button {
        margin: 5px 0;
      }
    }
  }
  ::v-deep .form_item_box {
    .ant-form-item-label {
      width: 50px;
    }
  }
</style>
